import numpy as np
import matplotlib.pyplot as plt


def loadData():
    points = np.genfromtxt("线性回归.csv", delimiter=",", skip_header=0, dtype=None)


points = []
for i in range(300):
    x = round(np.random.uniform(0, 20), 2)
    noise = np.random.normal(0, 1)
    y = round(0.825 * x + noise, 2)
    points.append([x, y])
    plt.scatter(x, y, c='r')
plt.show()


# step 1:实现计算误差函数
def compete_error_for_given_points(b, w, points):
    total_error = 0
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        total_error += (y - (w * x + b)) ** 2  # 均方误差
    return total_error / float(len(points))


# step 2:计算梯度和更新
def compete_gradient_and_update(b_current, w_current, lr, points):
    w_gradient = 0
    b_gradient = 0
    N = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        w_gradient += (2 / N) * x * ((w_current * x + b_current) - y)
        b_gradient += (2 / N) * ((w_current * x + b_current) - y)
    new_w = w_current - (lr * w_gradient)
    new_b = b_current - (lr * b_gradient)
    return [new_w, new_b]


# step 3：w and b ，loop
def gradient_desent_runner(w_start, b_start, lr, times, points):
    b = b_start
    w = w_start
    for i in range(times):
        w, b = compete_gradient_and_update(b, w, lr, np.array(points))
    return [w, b]


def run():
    lr = 0.001
    initial_b = 0
    initial_w = 0
    times = 1500
    print("Starting Giadient desent at w ={0},b ={1},error={2}"
          .format(initial_w, initial_b, compete_error_for_given_points(initial_b, initial_w, np.array(points))))
    print("Running:")
    [w, b] = gradient_desent_runner(initial_w, initial_b, lr, times, points)
    print("After {0} times w = {1},b = {2},error = {3}"
          .format(times, w, b, compete_error_for_given_points(b, w, np.array(points))))


if __name__ == '__main__':
    run()
